from chat.model.Action import Action
from chat.model.User import User

from ActionBase import ActionBase
from ActionExceptions import *
from Response import Response

class ActionTalk(ActionBase):
    _action_token = 'talk'
    
    _TARGET_KEY = 'target'
    _DATA_KEY = 'data'

    _ERROR_NO_DATA  = 0x0001
    
    def handle(self, postData):
        response = Response()

        actionTarget = postData.get(self._TARGET_KEY, None)
        actionData = postData.get(self._DATA_KEY, None)

        if actionData is None or len(actionData) == 0:
            response._status = self._ERROR_NO_DATA
            response._errors.append("No data specified.")
            return response

        actionData = ActionBase.strip_non_printable(actionData.replace("&", "&amp;").replace("<", "&lt;"). replace(">", "&gt;"));

        actionUser = User.verify_message(postData.get(self._USER_ID_TOKEN, None), postData.get(self._MESSAGE_KEY_TOKEN, None), postData.get(self._MESSAGE_HASH_TOKEN, None))
        if actionUser is None:
            raise ActionIntegrityException()
        
        actionChannel = User.verify_target(actionUser, actionTarget)
        if actionChannel is None:
            raise TargetException()  
        
        self._log_action(actionUser, actionChannel, actionData);
        
        return response
    
    def _log_action(self, user, target, data):
        action = Action()
        action.action = 'TALK'
        action.username = user.username
        action.username_id = user.identity_id
        action.target = target
        action.data = data
        action.save()